<template>
	<view class="v-code-group">
		<input type="number" @input="setCodeIndex" v-model="code.valueCode" maxlength="6" />
		<view class="send-button" :class="[code.stats ? 'sended' : '']" @tap="send">{{ code.stats ? code.time + ' s' : '发送' }}</view>
	</view>
</template>

<script>
import constant from '../../utils/Constant.js';
import showToast from '../../utils/ToastUtils.js';
export default {
	props: { phone: String, type: String },
	data() {
		return {
			deviceId: '',
			code: {},
			sended: false
		};
	},
	mounted() {
		this.code = {
			time: 60,
			stats: false,
			index: 0,
			inputArr: 0
		};
	},
	created() {
		uni.getSystemInfo({
			success: res => {
				this.deviceId = res.deviceId;
			}
		});
	},
	methods: {
		setCodeIndex(e) {
			if(e.detail.value.length===6){
				if (this.sended) {
					this.$emit('code', e.detail.value);
				} else {
					showToast('尚未发送验证码');
				}
			}
		},
		countDown() {
			this.code.stats = true;
			this.code.time = this.code.time - 1;
			let sendCode = setInterval(() => {
				if (this.code.time > 0) {
					this.code.time = this.code.time - 1;
				} else {
					this.code.time = 60;
					this.code.stats = false;
					clearInterval(sendCode);
				}
			}, 1000);
		},
		send() {
			if(!this.code.stats){
				uni.request({
					url: constant.baseHttpUri + constant.pathUri.smSend,
					data: {
						userName: this.phone,
						deviceId: this.deviceId,
						templateCode: this.type
					},
					method: 'POST',
					success: res => {
						if (res.data.code === constant.dataCode.OK) {
							showToast('验证码发送成功');
							this.countDown();
							if (!this.sended) {
								this.sended = true;
							}
						} else {
							showToast(res.data.msg);
						}
					},
					fail(r) {
						console.log(r);
					}
				});
			}
		}
	}
};
</script>

<style lang="less" scoped>
.v-code-group {
	margin: 30rpx 0 50rpx 0;
	display: flex;
	flex-direction: row;
	align-items: center;
	input {
		margin-right: 15rpx;
		width: 200rpx;
		height: 80rpx;
		border-bottom: 2rpx dotted #666666;
		text-align: center;
		font-size: 34rpx;
		font-weight: 500;
		color: #7088ff;
	}
	.send-button {
		margin-left: 10rpx;
		background: linear-gradient(270deg, #fc80a4 0%, #feb7ba 100%);
		padding: 0 30rpx;
		height: 62rpx;
		line-height: 62rpx;
		font-size: 30rpx;
		color: #ffffff;
		font-weight: 500;
		border-radius: 8rpx;
	}
	.sended {
		background: #999999;
	}
}
</style>
